package com.kgc.sbt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.sbt.api.WxPayApi;
import com.kgc.sbt.constant.SystemConstant;
import com.kgc.sbt.domain.OrderInfo;
import com.kgc.sbt.domain.TempOrderInfo;
import com.kgc.sbt.domain.VipRecord;
import com.kgc.sbt.util.RequestResult;
import com.kgc.sbt.util.ResultBuildUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * Created on 2021/6/23.
 * <p>
 * Author: yx
 * <p>
 * Description:
 */
@RestController
@Slf4j
@Api(tags = "微信支付接口，版本号：1.0.0")
public class WxPayController extends BaseController{

    @Reference
    private WxPayApi wxPayApi;

    // 静态注入redis
    private static Jedis jedis = new Jedis("127.0.0.1", 6379);

    static {
        // 用0库进行测试
        jedis.select(0);
    }

    /**
     *调用微信官方统一下单
     */
    @ApiOperation(value = "支付接口",notes = "需要传入订单号")
    @PostMapping("/wxpayOrder")

//    public RequestResult<Map<String, String>> wxpayOrder(HttpServletRequest request, @RequestParam String orderId,@RequestParam(required = false) BigDecimal totalFee) throws Exception{
    public RequestResult<Map<String, String>> wxpayOrder(HttpServletRequest request, @RequestParam @ApiParam(name = "orderId",value = "订单号",required = true) String orderId) throws Exception{


        //通过订单id查询订单详情
        TempOrderInfo orderInfo;
        String body = "";
        BigDecimal totalFee;
        if ("T".equals(orderId.substring(0,1))) {
            body = "腾讯充值-商品购买";
            // 如果订单在生成支付码之前失效
            if (StringUtils.isEmpty(orderInfo = wxPayApi.queryPayInfoByOrderId(orderId))){
                return ResultBuildUtil.fail("6944","无效的订单号");
            }
            totalFee = orderInfo.getPayAmount();
            totalFee = BigDecimal.valueOf(0.01);
        } else {
            // 会员充值类型
            body = "腾讯充值-会员充值";
            // 如果订单在生成支付码之前失效
            if (StringUtils.isEmpty(orderInfo = wxPayApi.queryVipPayInfoByOrderId(orderId))){
                return ResultBuildUtil.fail("6944","无效的订单号");
            }
            totalFee = orderInfo.getPayAmount();
        }

        // 获取统一下单接口参数xml字符串
        String wxpayOrderXmlStr = wxPayApi.getWxpayOrderParamsXmlStr(body, this.getRemoteIp(request), totalFee.multiply(new BigDecimal(100)).intValue(),orderId);
        log.info("------ 发送微信统一下单参数：{} ", wxpayOrderXmlStr);

        // 调用微信统一下单接口
        Map<String, String> wxpayOrderReturnMap = wxPayApi.send2WxpayUnifiedOrder(wxpayOrderXmlStr);
        log.info("------ 发送微信统一下单返回结果：{}", wxpayOrderReturnMap);

        // 统一返回下单结果
        Map<String, String> wxpayReturnData = new HashMap<>();
        // 同步解析微信下单返回结果
        if(SystemConstant.WXPAY_RETURN_SUCCESS.equals(wxpayOrderReturnMap.get("return_code"))
                && SystemConstant.WXPAY_RETURN_SUCCESS.equals(wxpayOrderReturnMap.get("result_code"))){
            // 交易类型
            wxpayReturnData.put("trade_type", wxpayOrderReturnMap.get("trade_type"));

            // 预支付交易会话标识
            wxpayReturnData.put("prepay_id", wxpayOrderReturnMap.get("prepay_id"));

            // 支付二维码
            wxpayReturnData.put("code_url", wxpayOrderReturnMap.get("code_url"));

            return ResultBuildUtil.success(wxpayReturnData);
            // TODO 支付过程中，订单失效。。。。。。应该支付失败。（未实现）
        }

        return ResultBuildUtil.fail();
    }


    /**
     * @author : yangxin
     * @return :
     * @description : 微信支付结果异步回调入口
     */
    @PostMapping("/wxpayNotify")
    @ApiOperation(value = "微信支付结果异步回调入口")
    public void wxpayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {

        log.info("----- 进入回调");

        // 解析微信官方支付结果回调内容
        StringBuffer wxpayNotifyStr = new StringBuffer();

        // 微信回调处理同步返回结果
        String wxpayResponseResultXmlStr = "";

        // 微信回调是以数据流的方式返回的，必须解析数据流
        try(InputStream inputStream = request.getInputStream()) {
            // 高效读取
            BufferedReader bfr = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line;
            while ((line = bfr.readLine()) != null){
                wxpayNotifyStr.append(line);
            }

            log.info("------ 微信异步回调支付结果：{}", wxpayNotifyStr.toString());

            //成功返回  SystemConstant.WXPAY_RESPONSE_RESULT_SUCCESS
            //失败返回  SystemConstant.WXPAY_RESPONSE_RESULT_FAIL
            wxpayResponseResultXmlStr = wxPayApi.resolveWxpayOrderNotify(wxpayNotifyStr.toString());


        } catch (IOException e){
            log.error("微信回调解析异常：{}", e.getMessage());
        }

        // 结果解析成功，同步给微信返回结果
        PrintWriter out = response.getWriter();
        out.write(wxpayResponseResultXmlStr);
        out.flush();
        out.close();
    }
}
